package com.yuyang.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyang.common.constant.OrderConstants;
import com.yuyang.common.exception.NoStockException;
import com.yuyang.common.to.SkuHasStockTo;
import com.yuyang.common.to.mq.OrderTo;
import com.yuyang.common.to.mq.SeckillOrderTo;
import com.yuyang.common.utils.PageUtils;
import com.yuyang.common.utils.Query;
import com.yuyang.common.utils.R;
import com.yuyang.common.vo.MemberResponseVo;
import com.yuyang.gulimall.order.dao.OrderDao;
import com.yuyang.gulimall.order.entity.OrderEntity;
import com.yuyang.gulimall.order.entity.OrderItemEntity;
import com.yuyang.gulimall.order.entity.PaymentInfoEntity;
import com.yuyang.gulimall.order.fegin.CartFeignService;
import com.yuyang.gulimall.order.fegin.MemberFeignService;
import com.yuyang.gulimall.order.fegin.ProductFeignService;
import com.yuyang.gulimall.order.fegin.WareFeignService;
import com.yuyang.gulimall.order.interceptor.LoginUserInterceptor;
import com.yuyang.gulimall.order.service.OrderItemService;
import com.yuyang.gulimall.order.service.OrderService;
import com.yuyang.gulimall.order.service.PaymentInfoService;
import com.yuyang.gulimall.order.to.OrderCreateTo;
import com.yuyang.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    PaymentInfoService paymentInfoService;

    ThreadLocal<OrderSubmitVo> orderConfirmVoThreadLocal = new ThreadLocal<>();


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<OrderEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        lambdaQueryWrapper.and(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(key), wrapper ->
                wrapper.eq(OrderEntity::getId, key).
                        or().like(OrderEntity::getReceiverName, key).
                        or().like(OrderEntity::getReceiverDetailAddress, key).
                        or().like(OrderEntity::getOrderSn, key));
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                lambdaQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageWithItems(Map<String, Object> params) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getMemberId, memberResponseVo.getId()).orderByDesc(OrderEntity::getId)
        );
        List<OrderEntity> orderEntities = page.getRecords().stream().peek(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn, order.getOrderSn()));
            order.setItemEntities(orderItemEntities);
        }).collect(Collectors.toList());

        page.setRecords(orderEntities);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     *
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(infoEntity);

        //2、修改订单的状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功状态
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo, OrderConstants.OrderStatusEnum.PAYED.getCode());
        }
        //3、修改工作单和库存信息
        R r = wareFeignService.reduceStock(vo.getOut_trade_no());
        if (r.getCode() != 0) {

        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderConstants.OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setTotalAmount(multiply);
        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderId(orderEntity.getId());
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        //TODO 获取当前SKU的详细信息进行设置  productFeignService.getSpuInfoBySkuId()
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());
        orderItemService.save(orderItemEntity);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        //获取主线程的请求上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            //会员收获地址列表
            R address = memberFeignService.getMemberReceiveAddress(memberResponseVo.getId());
            if (address.getCode() == 0) {
                List<MemberAddressVo> data = address.getData("data", new TypeReference<List<MemberAddressVo>>() {
                });
                orderConfirmVo.setMemberAddressVos(data);
            }
        }, executor);

        CompletableFuture<Void> orderItemFuture = CompletableFuture.runAsync(() -> {
            //每个异步任务共享主线程的上下文
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //所有选中的购物项
            R checkItems = cartFeignService.getCheckedItems();
            if (checkItems.getCode() == 0) {
                List<OrderItemVo> data = checkItems.getData("data", new TypeReference<List<OrderItemVo>>() {
                });
                orderConfirmVo.setItems(data);
            }
        }, executor).thenRunAsync(() -> {
            //设置库存
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.hasStockBySkuIds(skuIds);
            List<SkuHasStockTo> data = r.getData(new TypeReference<List<SkuHasStockTo>>() {
            });
            orderConfirmVo.setStocks(data.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock)));
        }, executor);


        //优惠券（会员积分）
        orderConfirmVo.setIntegration(memberResponseVo.getIntegration());
        //TODO 防重令牌
        String uuid = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVo.setOrderToken(uuid);
        stringRedisTemplate.opsForValue().set(OrderConstants.ORDER_TOKEN_CACHE_PREFIX + memberResponseVo.getId(), uuid);

        CompletableFuture.allOf(addressFuture, orderItemFuture).get();
        return orderConfirmVo;
    }

    //    @GlobalTransactional 高并发不适用 使用可靠消息 +最终一致性方案
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        orderConfirmVoThreadLocal.set(vo);
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long execute = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Collections.singletonList(OrderConstants.ORDER_TOKEN_CACHE_PREFIX + memberResponseVo.getId()),
                vo.getOrderToken());
        if (execute == 0L) {
            //令牌校验失败
            responseVo.setCode(1);
        } else {
            //创建订单、比较价格、锁库存
            //1、创建订单，订单项等信息
            OrderCreateTo order = createOrder();
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //价格对比成功
                //TODO 3、保存订单
                saveOrder(order);
                //4、锁库存
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> collect = order.getOrderItems().stream().map((orderItem -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setCount(orderItem.getSkuQuantity());
                    orderItemVo.setSkuId(orderItem.getSkuId());
                    return orderItemVo;

                })).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);

                R r = wareFeignService.skuWareLock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //锁成功
                    responseVo.setOrder(order.getOrder());
                    //TODO 5、扣减积分
//                    int i= 1/0; //远程调用成功但只有本地事务回滚 使用分布式事务
                    //TODO 订单创建完成向MQ发送消息 自动解锁库存
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                } else {
                    //锁库存失败
                    responseVo.setCode(3);
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                responseVo.setCode(2);
            }
        }
        return responseVo;

    }

    //订单过期自动关闭
    @Transactional
    @Override
    public void closeOrder(OrderEntity order) {
        //查询最新的订单状态
        String orderSn = order.getOrderSn();
        OrderEntity byOrderSn = getByOrderSn(orderSn);
        if (byOrderSn.getStatus() == OrderConstants.OrderStatusEnum.CREATE_NEW.getCode()) {
            OrderEntity update = new OrderEntity();
            update.setId(order.getId());
            update.setStatus(OrderConstants.OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            //给库存解锁队列发送消息，订单已经取消
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(byOrderSn, orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    @Override
    public OrderEntity getByOrderSn(String orderSn) {
        return this.getOne(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderSn, orderSn));
    }

    @Override
    public PayVo payOrder(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getByOrderSn(orderSn);
        payVo.setOut_trade_no(orderSn);
        String totalAmount = orderEntity.getTotalAmount().setScale(2, BigDecimal.ROUND_UP).toString();
        payVo.setTotal_amount(totalAmount);
        List<OrderItemEntity> orderItemEntities = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn, orderSn));
        OrderItemEntity orderItemEntity = orderItemEntities.get(0);
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        payVo.setSubject(orderItemEntity.getSkuName());
        return payVo;
    }


    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItemEntities = order.getOrderItems().stream().peek(orderItemEntity -> orderItemEntity.setOrderId(orderEntity.getId())).collect(Collectors.toList());
        orderItemService.saveBatch(orderItemEntities);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        String orderSn = IdWorker.getTimeId();
        //1、创建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        //2、构建所有订单项数据
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        //3、计算价格、积分等相关
        if (itemEntities != null && itemEntities.size() > 0) {
            computePrice(orderEntity, itemEntities);

            orderCreateTo.setOrderItems(itemEntities);
        }
        orderCreateTo.setOrder(orderEntity);

        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额，叠加每一个订单项的总额信息

        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
//            Integer growth = entity.getGiftGrowth();
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }
        //订单价格相关
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);
        //设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        R checkedItems = cartFeignService.getCheckedItems();
        List<OrderItemVo> orderItemVos = checkedItems.getData(new TypeReference<List<OrderItemVo>>() {
        });
        if (orderItemVos != null && orderItemVos.size() > 0) {
            List<OrderItemEntity> collect = orderItemVos.stream().map((orderItemVo -> {
                OrderItemEntity orderItemEntity = buildOrderItem(orderItemVo);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            })).collect(Collectors.toList());
            return collect;
        }
        return null;


    }

    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1、订单信息：订单号 v
        //2、商品的SPU信息  V
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //3、商品的sku信息  v
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息[不做]
        //5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额。 总额-各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }

    private OrderEntity buildOrder(String orderSn) {
        OrderEntity entity = new OrderEntity();

        entity.setOrderSn(orderSn);
        OrderSubmitVo orderSubmitVo = orderConfirmVoThreadLocal.get();
        //获取收货地址信息
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        entity.setMemberId(memberResponseVo.getId());
        entity.setMemberUsername(memberResponseVo.getUsername());

        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

        //设置订单的相关状态信息
        entity.setStatus(OrderConstants.OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

}